package com.westar.core.services;

import com.alibaba.fastjson.JSONObject;
import com.google.common.io.BaseEncoding;
import com.westar.base.cons.Constant;
import com.westar.base.exceptions.SelfHttpException;
import com.westar.base.model.AccountLimit;
import com.westar.base.model.UserInfo;
import com.westar.base.pojo.WestarResult;
import com.westar.base.util.CodeUtil;
import com.westar.base.util.TokenUtil;
import com.westar.base.util.WestarHttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 登录操作
 */
@Service
public class LoginService {

    private static Logger logger = LoggerFactory.getLogger( LoginService.class);

    @Autowired
    private UserInfoService userinfoService;

    @Autowired
    private AccountLimitService accountLimitService;

    /**
     * 获取用户认证信息
     * @param account 账号
     * @param password 密码
     * @param times 次数 0代表第一次调用 1代表从userInfo表获取 2代表从userDepAreaRelate获取
     * @param prePasswdList
     * @return
     */
    public WestarResult getToken(String account, String password, int times, List<String> prePasswdList) {

        //查询密码的次数，判定管是否需要限定时间再次登录
        int errorCount = accountLimitService.countAccountLimit(account);
        if(errorCount > 5 ){
            return WestarResult.build(-1,"密码错误超过五次！");
        }

        String token = null;
        try {
            //获取token
            token = TokenUtil.initToken(account,password, Constant.MODEL_OAUTHUI);
            JSONObject jsonObject = new JSONObject();
            //保存用户
            if(StringUtils.isNotEmpty(token)){
                //修改用户的加密密码
                userinfoService.updateUserInfo(account,password);
                //PasswdMd5库
                userinfoService.updatePasswdMd5(password);
                //修改用户的加密密码
                userinfoService.updateUserDepAreaRelate(account,password);

                UserInfo sessionuser = userinfoService.getUserInfoByAccount(account);

                sessionuser.setPasswd(password);
                TokenUtil.updateSessionUser(token,sessionuser);

                jsonObject.put("passwd",password);
                jsonObject.put("md5",sessionuser.getMd5());
            }
            jsonObject.put("token",token);

            //登录成功，删除所有的密码错误记录
            accountLimitService.deleteAccountLimit(account);

            return new WestarResult(jsonObject.toJSONString());
        } catch (IOException e) {
            logger.error( "中间件访问一体化平台,网络错误!" );
            return WestarResult.build(-1,"中间件访问一体化平台出错!");
        } catch (SelfHttpException e) {
            Integer code = e.getCode();
            if( code.equals(SelfHttpException.PAGE_NOT_FOUND)){
                return WestarResult.build(-1,"中间件访问一体化平台页面已迁移!");
            }else if(code.equals(SelfHttpException.LOGIN_ERROR)){
                prePasswdList.add(password);
                return handleLoginError(account, times,prePasswdList,errorCount);
            }else if(code.equals(SelfHttpException.PAGE_RE_LOGIN)){
                return this.getToken(account,password,0,prePasswdList);
            }else{
                return WestarResult.build(-1,"中间件访问一体化平台出错!");
            }
        }
    }

    /**
     * 处理密码错误的情况
     * @param account 账号
     * @param times 次数 0代表第一次调用 1代表从userInfo表获取 2代表从userDepAreaRelate获取
     * @return
     */
    private WestarResult handleLoginError(String account, int times,List<String> prePasswd,Integer errorCount) {
        if(times == 0){
            //第一次验证失败后，从数据库userInfo再次获取
            String dbPasswd = userinfoService.getPasswdByAccount(account);
            if(null == dbPasswd){
                accountLimitService.addAccountLimit(account,errorCount);
                return WestarResult.build(-1,"账号或密码错误！");
            }

            if(!prePasswd.contains(dbPasswd)){
                if(!dbPasswd.equals("-")){
                    return getToken(account, dbPasswd,1,prePasswd);
                }else{
                    accountLimitService.addAccountLimit(account,errorCount);
                    return WestarResult.build(-1,"账号或密码错误！");
                }
            }else{
                dbPasswd = userinfoService.getPasswdByAccountWithMd5(account);
                if(null!=dbPasswd && !prePasswd.contains(dbPasswd) ){
                    return getToken(account, dbPasswd,2,prePasswd);
                }else{
                    accountLimitService.addAccountLimit(account,errorCount);
                    return WestarResult.build(-1,"账号或密码错误！");
                }
            }
        }else if(times == 1){
            //从userDepAreaRelate获取相关账户数据
            String dbPasswd = userinfoService.getPasswdByAccountWithMd5(account);
            if(null != dbPasswd && !prePasswd.contains(dbPasswd)){
                return getToken(account, dbPasswd,1,prePasswd);
            }else{
                accountLimitService.addAccountLimit(account,errorCount);
                return WestarResult.build(-1,"账号或密码错误！");
            }
        }else{
            accountLimitService.addAccountLimit(account,errorCount);
            return WestarResult.build(-1,"账号或密码错误！");
        }
    }

}
